<?php
/**
 * Brokinginquiries Controller
 *
 * This file will take care of file uploads (with rich text editor integration).
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class BrokinginquiriesController extends AppController {
/**
 * Controller name
 *
 * @var string
 * @access public
 */
    public $name = 'Brokinginquiries';
/**
 * Models used by the Controller
 *
 * @var array
 * @access public
 */
    public $uses = array('Brokinginquiry', 'Inquirer', 'Aihcontact','Contacttype');
/**
 * Helpers used by the Controller
 *
 * @var array
 * @access public
 */
    public $helpers = array('Filemanager', 'Text', 'Image');

/**
 * Uploads directory
 *
 * relative to the webroot.
 *
 * @var string
 * @access public
 */
    public $uploadsDir = 'uploads';

    protected $paginate = array(
        'limit' => 10,
        );

/**
 * Before executing controller actions
 *
 * @return void
 * @access public
 */
    public function beforeFilter() {
        parent::beforeFilter();

        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
    }

/**
 * Admin index
 *
 * @return void
 * @access public
 */
    public function admin_index() {
        $this->set('title_for_layout', __('BROKING INQUIRY LIST'));
        
        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $contacttypes = $this->Aihcontact->find('first',array('conditions' => array('Aihcontact.id' => 'Producer')));

        $this->Brokinginquiry->recursive = 0;
        $this->paginate['Brokinginquiry']['order'] = 'Brokinginquiry.created DESC';
        
        $this->set('brokinginquiries', $this->paginate());
    }

    public function admin_search() {
        $this->set('title_for_layout', __('BROKING INQUIRY SEARCH'));
        
        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);
        $q = $this->params['named']['q'];
        $this->set('q', $q);
        
        $inquirer_id = $this->Inquirer->find('first', array(
            'conditions' => array(
                'Inquirer.name LIKE' => '%'.$q.'%',
            ),
        ));
        $this->Brokinginquiry->recursive = 0;
        if($q == 'all'){
            
        }else{
            $this->paginate['Brokinginquiry']['conditions'] = array('OR' => array(
                                                            'Brokinginquiry.account_name LIKE' => '%'.$q.'%',
                                                            'Brokinginquiry.inquirer_id LIKE' => $inquirer_id['Inquirer']['id'],
                                                            ));
        }
        $this->paginate['Brokinginquiry']['order'] = 'Brokinginquiry.created DESC';

        $this->set('brokinginquiries', $this->paginate());
    }
    
/**
 * Admin add
 *
 * @return void
 * @access public
 */
    public function admin_add() {
        
        $scriptDate = $this->datePicker();
        $this->set('scriptDate', $scriptDate);
        
        $scriptDate = $this->dateDefault();
        $this->set('scriptDateDefault', $scriptDate);
        
        $this->set('title_for_layout', __('BROKING INQUIRY DETAIL'));

        if (!empty($this->request->data)) {
            if($this->request->data['Brokinginquiry']['file']['name'] != '') {
                $file = $this->request->data['Brokinginquiry']['file'];
                unset($this->request->data['Brokinginquiry']['file']); 
                if($file['type'] == 'application/msword' 
                        || $file['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
                        || $file['type'] == 'application/excel' 
                        || $file['type'] == 'application/vnd.ms-excel' 
                        || $file['type'] == 'application/x-excel' 
                        || $file['type'] == 'application/x-msexcel' 
                        || $file['type'] == 'application/pdf'
                        || $file['type'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                        || $file['type'] == 'text/plain') {
                    // check if file with same path exists
                    $destination = WWW_ROOT . $this->uploadsDir . DS . $file['name'];
                    if (file_exists($destination)) {
                        $newFileName = uniqid() . '-' . $file['name'];
                        $destination = WWW_ROOT . $this->uploadsDir . DS . $newFileName;
                    } else {
                        $newFileName = $file['name'];
                    }

                    $this->request->data['Brokinginquiry']['attached'] = $newFileName;
                    $this->request->data['Brokinginquiry']['mime_type'] = $file['type'];
                    $this->request->data['Brokinginquiry']['path'] = '/' . $this->uploadsDir . '/' . $newFileName;

                    $this->request->data['Brokinginquiry']['inquirer_id'] = $this->request->data['Inquirer']['Inquirer'];

                    $this->request->data['Brokinginquiry']['date_from'] = date('Y-m-d', strtotime($this->request->data['Brokinginquiry']['date_from']));
                    $this->request->data['Brokinginquiry']['date_to'] = date('Y-m-d', strtotime($this->request->data['Brokinginquiry']['date_to']));

                    $poidsMax = ini_get('post_max_size');
                    if((intval($poidsMax)*1024*1024) > $file['size']){
                        $this->Brokinginquiry->create();
                        if ($this->Brokinginquiry->save($this->request->data)) {
                            $contactsids[] = $this->data['Inquirer']['Inquirer'];
                            $this->Brokinginquiry->lock($contactsids, 'cc_aihcontacts', 1);
                            
                            move_uploaded_file($file['tmp_name'], $destination);
                            
                            //$this->Session->setFlash(__('The Broking Inquiry has been saved'), 'default', array('class' => 'success'));

                            $this->redirect(array('action'=>'index'));
                        } else {
                            $this->Session->setFlash(__('The Broking Inquiry could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                        } 
                    }else{
                        $this->Session->setFlash(__('Can not upload file over ' + $poidsMax), 'default', array('class' => 'error'));
                    }
                } else {
                    $this->Session->setFlash(__('Attachment allow the following formats *.pdf *.doc, *.docx, *.xls, *.xlsx, *.txt. Please, try again.'), 'default', array('class' => 'error'));
                }
            } else {
                //$this->Session->setFlash(__('No file uploaded, try again.'), 'default', array('class' => 'error'));
                $this->request->data['Brokinginquiry']['inquirer_id'] = $this->request->data['Inquirer']['Inquirer'];
                $this->request->data['Brokinginquiry']['date_from'] = date('Y-m-d', strtotime($this->request->data['Brokinginquiry']['date_from']));
                $this->request->data['Brokinginquiry']['date_to'] = date('Y-m-d', strtotime($this->request->data['Brokinginquiry']['date_to']));
                    
                $this->Brokinginquiry->create();
                if ($this->Brokinginquiry->save($this->request->data)) {
                    $contactsids[] = $this->data['Inquirer']['Inquirer'];
                    $this->Brokinginquiry->lock($contactsids, 'cc_aihcontacts', 1);
                    
                    $this->redirect(array('action'=>'index'));
                }
            }
        } 
        
        $contacttypes = $this->Contacttype->find('first',array('conditions' => array('Contacttype.name' => 'Producer')));
        
        $contacttype_id = $contacttypes['Contacttype']['id'];
        
        $inquirers = $this->Aihcontact->find('list',array('fields' => array('Aihcontact.id', 'Aihcontact.name'), 'order' => array('Aihcontact.name ASC'), 'conditions' => array('Aihcontact.contacttype_id' => $contacttype_id)));
        
        $this->set(compact('inquirers'));
    }

/**
 * Admin edit
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('BROKING INQUIRY DETAIL'));
        
        $scriptDate = $this->datePicker();
        $this->set('scriptDate', $scriptDate);

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Broking Inquiry'), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->request->data)) {
            $this->request->data['Brokinginquiry']['date_from'] = date('Y-m-d', strtotime($this->request->data['Brokinginquiry']['date_from']));
            $this->request->data['Brokinginquiry']['date_to'] = date('Y-m-d', strtotime($this->request->data['Brokinginquiry']['date_to']));
                
            $file = '';
            $old_file = $this->request->data['Brokinginquiry']['attached'];
            if($this->request->data['Brokinginquiry']['file']['name'] != '') {
                $file = $this->request->data['Brokinginquiry']['file'];
                
            } else {
                unset($this->request->data['Brokinginquiry']['attached']);
                unset($this->request->data['Brokinginquiry']['mime_type']);
            }
            unset($this->request->data['Brokinginquiry']['file']);

            $bool = true;
            
            if($file != '') {
                if($file['type'] == 'application/msword' 
                        || $file['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
                        || $file['type'] == 'application/excel' 
                        || $file['type'] == 'application/vnd.ms-excel' 
                        || $file['type'] == 'application/x-excel' 
                        || $file['type'] == 'application/pdf'
                        || $file['type'] == 'application/x-msexcel' 
                        || $file['type'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                        || $file['type'] == 'text/plain') {
                    // check if file with same path exists
                    $destination = WWW_ROOT . $this->uploadsDir . DS . $file['name'];
                    $old_destination = WWW_ROOT . $this->uploadsDir . DS . $old_file;
                    if (file_exists($destination)) {
                        $newFileName = uniqid() . '-' . $file['name'];
                        $destination = WWW_ROOT . $this->uploadsDir . DS . $newFileName;
                    } else {
                        $newFileName = $file['name'];
                    }
                    $this->request->data['Brokinginquiry']['attached'] = $newFileName;
                    $this->request->data['Brokinginquiry']['mime_type'] = $file['type'];
                    
                    $this->request->data['Brokinginquiry']['path'] = '/' . $this->uploadsDir . '/' . $newFileName;
                } else {
                    $bool = false;
                    $this->Session->setFlash(__('Attachment allow the following formats *.pdf *.doc, *.docx, *.xls, *.xlsx, *.txt. Please, try again.'), 'default', array('class' => 'error'));
                    
                }

            }
            if($bool) {
                $this->request->data['Brokinginquiry']['inquirer_id'] = $this->request->data['Inquirer']['Inquirer'];
                    if ($this->Brokinginquiry->save($this->request->data)) {
                        //php_debug($this->request->data);
                        $oldcontactsids[] = $this->data['oldInquirerID'];
                        $this->Brokinginquiry->lock($oldcontactsids, 'cc_aihcontacts', -1);
                        $contactsids[] = $this->data['Inquirer']['Inquirer'];
                        $this->Brokinginquiry->lock($contactsids, 'cc_aihcontacts', 1);
                        if($file != '') {
                            $poidsMax = ini_get('post_max_size');
                            if((intval($poidsMax)*1024*1024) > $file['size']){
                                move_uploaded_file($file['tmp_name'], $destination);
                                if(file_exists($old_destination)) {
                                    unlink($old_destination);
                                }
                            }else{
                                $this->Session->setFlash(__('Can not upload file over ' + $poidsMax), 'default', array('class' => 'error'));
                            }
                            
                        }
                        //$this->Session->setFlash(__('The Broking Inquiry has been saved'), 'default', array('class' => 'success'));
                        $this->redirect(array('action'=>'index'));
                    } else {
                        $this->Session->setFlash(__('The Broking Inquiry could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                    }
                
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Brokinginquiry->read(null, $id);
            $contacttypes = $this->Contacttype->find('first',array('conditions' => array('Contacttype.name' => 'Producer')));
            $contacttype_id = $contacttypes['Contacttype']['id'];
            $inquirers = $this->Aihcontact->find('list',array('order' => array('Aihcontact.name ASC'), 'conditions' => array('Aihcontact.contacttype_id' => $contacttype_id)));
            $this->set(compact('inquirers'));
        }

    }

/**
 * Admin delete
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Broking Inquiry'), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index'));
        }

        $brokinginquiry = $this->Brokinginquiry->find('first', array(
            'conditions' => array(
                'Brokinginquiry.id' => $id,
            ),
        ));

        if (isset($brokinginquiry['Brokinginquiry'])) {
            if ($this->Brokinginquiry->delete($id)) {
                
                $contactsids[] = $brokinginquiry['Brokinginquiry']['inquirer_id'];
                $this->Brokinginquiry->lock($contactsids, 'cc_aihcontacts', -1);
                
                if(file_exists(WWW_ROOT . $this->uploadsDir . DS . $brokinginquiry['Brokinginquiry']['attached'])) {
                    unlink(WWW_ROOT . $this->uploadsDir . DS . $brokinginquiry['Brokinginquiry']['attached']);
                }
                //$this->Session->setFlash(__('Broking Inquiry deleted'), 'default', array('class' => 'success'));
                $this->redirect(array('action'=>'index'));
            }
        } else {
            $this->Session->setFlash(__('Invalid id for Broking Inquiry'), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index'));
        }
    }
    
    public function admin_check_unique($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $banks = $this->Brokinginquiry->find('first', array('fields' => array('Brokinginquiry.risk_ref'), 'conditions' => array('Brokinginquiry.risk_ref' => $id,)));
            if ($banks) {
                $success = true;
                $success = $this->Brokinginquiry->encodeData(array('success' => $success, 'isExsist' => '1'), array('json' => true, 'trim' => false));
            }else{
                $success = true;
                $success = $this->Brokinginquiry->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Brokinginquiry->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
        }
        $this->set('success', $success);
    }
    
    public function datePicker() {
        $output = "$(function() {
                        $('#BrokinginquiryDateFrom').datepicker({ changeYear: true });
                        $('#BrokinginquiryDateTo').datepicker({ changeYear: true });
                        return false;
                    });";
        return $output;
    }
    
    public function dateDefault() {
        $output = "$(function() {
                        var d = new Date();
                        var twoDigitMonth = ((d.getMonth().length+1) === 1)? (d.getMonth()+1) : '0' + (d.getMonth()+1);
                        var todaystring = twoDigitMonth + '/' + d.getDate() + '/' + d.getFullYear();
                        $('#BrokinginquiryDateFrom').val(todaystring);
                        $('#BrokinginquiryDateTo').val(todaystring);
                    });";
        return $output;
    }
    
    public function scriptSearchBox(){
        $output = "
            $(function() {
                $('#search_button').click(function(){
                    if($('#search_text').val() == ''){
                        $(location).attr('href','" . Router::url('/admin/brokinginquiries/search/q:', true) . "' + 'all');
                    }else{
                        $(location).attr('href','" . Router::url('/admin/brokinginquiries/search/q:', true) . "' + $('#search_text').val());  
                    }
                });
                $('#search_text').keypress(function(event) {
                    if ( event.which == 13 ) {
                        event.preventDefault();
                        $(location).attr('href','" . Router::url('/admin/brokinginquiries/search/q:', true) . "' + $('#search_text').val());
                    }
                });
            });";
        return $output;
    }
}
?>